import math
import os
import re
import struct
import threading
import pandas as pd
import numpy as np
import time
from commen.log import Logger
import openpyxl
import datetime
import commen.config


def ImuDatacontinuity():
    # ---------读取config文件获取筛选字段内容--------------------------
    mpukey = commen.config.global_config.getRaw('keywords', 'suanfagnss')
    caninskey = commen.config.global_config.getRaw('keywords', 'cankeygnss')

    # ---------读取config文件获取筛选字段内容--------------------------
    logger = Logger(logger='TestMylog').getlog()
    # -----------------------创建excel--------------------------------------------
    # 获取当前时间
    time_now = time.strftime("%Y%m%d-%H%M", time.localtime())
    # 获取当前路径
    result_root = os.getcwd()
    root = os.getcwd()
    result_path = result_root + r'\result' + "\\" + time_now
    log_path = root + r'\original-logfile' + '\\'
    # -----遍历对比log路径获取要对比的文件名路径信息----------------------
    for root, dirs, files in os.walk(log_path):
        for file in files:
            if "Data" in file:
                aa = os.path.join(root, file)
            if "can" in file:
                bb = os.path.join(root, file)

    # -----遍历对比log路径获取要对比的文件名路径信息----------------------
    book = openpyxl.Workbook()  # 打开一个将写的文件
    sheet = book.create_sheet(index=0)  # 在将写的文件创建sheet
    saveExcel = result_path + "GNSS系统时间延时验证.xlsx"
    sheet.cell(1, 2).value = "mpu上GNSS数据的系统时间T1"
    sheet.cell(1, 3).value = "can上GNSS数据系统时间T2"
    # sheet.cell(1, 4).value = "mcu发送GNSS数据到can时间T2"
    sheet.cell(1, 4).value = "T2-T1时延"

    row = 1
    # -----------------------创建excel--------------------------------------------

    canfile = open(bb, 'r', encoding='gbk')  # 打开can.log目标文件
    dataprocfile = open(aa, 'r', encoding='UTF-8')  # 打开dataproc.log文件
    logger.info("打开目标文件")
    canlines = canfile.readlines()
    mpulines = dataprocfile.readlines()
    logger.info("获取内容")

    mpusystemtimelist = []  # mpu数据的系统时间
    cansystemtimelist = []  # can数据的系统时间
    mpu_utctimelist = []# mpuutc时间
    can_utctimelist = []# canutc时间
    mcu_to_can_time = []
    logger.info("开始逐行读取")

    for lines in mpulines:  # 对内容 进行逐行读取


        if mpukey in lines:  # 通过关键字获取数据信息并存入到list中

            mpusystemtime = lines[:lines.index("<thread")]
            mpusystemtimelist.append(mpusystemtime.rstrip())
            mpumessage = lines.split("+0:")
            mpumessage1 = mpumessage[1].lstrip().replace(" ", "").replace("-", "").replace("+10:", "").replace("+20:","").replace("+30:", "").replace("+40:", "").replace("+50:", "").replace("+60:", "").replace("+70:", "").replace("+80:", "").replace(")", "")
            mpu_utctimelist.append(mpumessage1.rstrip()[5:16])

    for canline in canlines:   # 对内容 进行逐行读取
        if caninskey in canline:# 通过关键字获取数据信息并存入到list中
            systemtime = canline[:canline.index("Rx")]
            cansystemtimelist.append(systemtime.rstrip())
            canmessage = canline.split("s-fd-brs 64")
            caninsdatamessage = canmessage[1].rstrip()
            caninsdatamessage = caninsdatamessage.lstrip()
            caninsdatamessage = caninsdatamessage.replace(" ","")
            caninsdatamessage = caninsdatamessage[4:15]
            can_utctimelist.append(caninsdatamessage)
            utctime = int(canmessage[1].replace(" ","").rstrip()[-12:-1], 16)  # 把16进制时间字符串转换成十进制
            mcu_to_can_time.append(utctime)

    for i in mpu_utctimelist:
        if i == "00000000000":
            continue
        if i in can_utctimelist:
            logger.info("开始进行对比")
            row = row+1
            mpu_number = mpu_utctimelist.index(str(i))
            can_number = can_utctimelist.index(str(i))
            date_add = mpusystemtimelist[mpu_number].split(" ")[0]
            t1 = datetime.datetime.strptime(mpusystemtimelist[mpu_number], '%Y-%m-%d %H:%M:%S.%f')
            t2 = datetime.datetime.strptime(date_add+" "+cansystemtimelist[can_number], '%Y-%m-%d %H:%M:%S:%f')
            # if mcu_to_can_time[can_number] == 0:
            #     continue

            # receivetime_old = bin(int(mcu_to_can_time[can_number]))  # 十进制字符串转换成二进制
            # # -------------------------二进制字符串转换成整数并拼接成时间------------------------------------
            #
            # year = pd.to_datetime("1980-01-06") + pd.DateOffset(days=int(receivetime_old[0:16], 2))
            # year = year.strftime('%Y-%m-%d')
            # hour = str(int(receivetime_old[16:22], 2))
            # minute = str(int(receivetime_old[22:28], 2))
            # seconds = str(int(receivetime_old[28:34], 2))
            # milliseconds = str(int(receivetime_old[34:], 2))
            # if int(hour) < 10:
            #     hour = "0" + str(hour)
            # if int(minute) < 10:
            #     minute = "0" + str(minute)
            # if int(seconds) < 10:
            #     seconds = "0" + str(seconds)
            # if int(milliseconds) < 10:
            #     milliseconds = "00" + str(milliseconds)
            # if 10 <= int(milliseconds) < 100:
            #     milliseconds = "0" + str(milliseconds)
            # sf_receivetime = year + " " + hour + ":" + minute + ":" + seconds + "." + milliseconds
            #
            # t2 = datetime.datetime.strptime(sf_receivetime, '%Y-%m-%d %H:%M:%S.%f')
            sheet.cell(row, 2).value = mpusystemtimelist[mpu_number]
            sheet.cell(row, 3).value = cansystemtimelist[can_number]
            # sheet.cell(row, 4).value = sf_receivetime
            try:

                t1 = int(time.mktime(t1.timetuple()) * 1000.0 + t1.microsecond / 1000.0)
                t2 = int(time.mktime(t2.timetuple()) * 1000.0 + t2.microsecond / 1000.0)
                deltat = int(t2) - int(t1) - 8*60*60*1000
                sheet.cell(row, 4).value = deltat
            except:
                sheet.cell(row, 4).value = str(int((t2 - t1).microseconds / 1000))



    # ----------------------将对比的数据写入excel---------------------------------
    book.save(saveExcel)
    # ----------------------将对比的数据写入excel---------------------------------

ImuDatacontinuity()




